package cn.controller;

import cn.dao.UploadDao;
import cn.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * Created by wsx on 2017/1/6.
 */
@Controller
public class UploadController {
    @Autowired
    private UploadService upservice;

    @RequestMapping(value = "/upload", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String index() {
        return "upload";
    }

    @RequestMapping(value = "/uploadfile")
    @ResponseBody
    public void uploadfile(HttpServletRequest req, HttpServletResponse resp) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            if (multipartFile.getSize() > 524288000) {
                resp.getWriter().print(new String("文件过大"));
                return;
            }
            String realPathprefix = req.getSession().getServletContext().getRealPath("filedic");
            File f = new File(realPathprefix);
            if (!f.exists()) {
                f.mkdir();
            }
            String originalFilename = multipartFile.getOriginalFilename();
            String newname = String.valueOf(System.currentTimeMillis());
            String realPath = realPathprefix + File.separator + newname;
            System.out.println(realPath);
            String temp = upservice.addfile(originalFilename,newname,multipartRequest);
            if("true" != temp){
                resp.getWriter().print(new String(temp));
                return;
            }
            File targetFile = new File(realPath);
            multipartFile.transferTo(targetFile);
            resp.getWriter().print(new String("上传成功"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
